package com.example.controller;

import com.example.util.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class SessionController {
    // 设置Cookie
    @GetMapping("cookie1")
    public Result cookie(HttpServletResponse response) {
        response.addCookie(new Cookie("login_username", "zhangsan2"));
        return Result.success();
    }

    @GetMapping("cookie2")
    public Result session(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("login_username")) {
                    log.info("浏览器自动带过来的Cookie: login_username={}", cookie.getValue());
                    return Result.success(cookie.getValue());
                }
            }
        }
        return Result.success();
    }

    @GetMapping("session1")
    public Result session1(HttpSession session) {
        log.info("HttpSession-1: {}", session.hashCode());
        session.setAttribute("login_username", "zhangsan2");
        return Result.success();
    }
    @GetMapping("session2")
    public Result session2(HttpServletRequest request) {
        HttpSession session = request.getSession();
        log.info("HttpSession-2: {}", session.hashCode());

        Object loginUsername = session.getAttribute("login_username");
        log.info("Session 中的登录名：loginUsername: {}", loginUsername);
        return Result.success(loginUsername);
    }
}